package com.frxuexi.park2303.news

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.base.entity.NewsBeanItem
import com.frxuexi.base.http.Const
import com.frxuexi.base.mvi.BaseActivity
import com.frxuexi.base.mvi.RequestType
import com.frxuexi.base.mvi.UiState
import com.frxuexi.base.utils.GlideUtil
import com.frxuexi.park2303.R
import com.frxuexi.park2303.databinding.ActivityNewsUpdateBinding
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = "/app/NewsUpdateActivity")
@AndroidEntryPoint
class NewsUpdateActivity : BaseActivity<ActivityNewsUpdateBinding,NewsIntent,NewsViewModel>() {
    @Autowired
    lateinit var nid:String

    var type=""
    var list= mutableListOf<String>()
    val typeList = mutableListOf<String>("园区新闻", "公告")
    override fun getVM(): NewsViewModel {
        return viewModels<NewsViewModel>().value
    }

    override fun getBind(): ActivityNewsUpdateBinding {
        return ActivityNewsUpdateBinding.inflate(layoutInflater)
    }

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        when(it.type){
                            RequestType.DEFAULT->{
                                val item = it.data as NewsBeanItem
                                binding.bean=item
                                list.addAll(item.images)
                                if(item.images.size>0){
                                    GlideUtil.loadRoundImage(binding.newupIv,item.images.get(0))
                                }


                                if(!typeList.contains(item.type)){
                                    typeList.add(0,item.type)
                                }
                                type=typeList.get(0)
                                val adapter = ArrayAdapter(
                                    this@NewsUpdateActivity,
                                    android.R.layout.simple_spinner_item,
                                    typeList
                                )
                                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                                binding.newupType.adapter=adapter

                            }
                            RequestType.UPLOAD->{
                                val name = it.data.toString().split(":")[1]
                                list.clear()
                                list.add("http://10.161.9.80:2209/images/news/${
                                    SPUtils.getInstance().getInt(
                                        Const.UID)}/${name}")
                            }
                            RequestType.UPDATE->{
                                ToastUtils.showLong("修改成功")
                                finish()
                            }

                            else -> {}
                        }

                    }
                    else -> {}
                }
            }

        }
    }

    override fun initView() {
        binding.newupHead.apply {
            headBack.setOnClickListener {
                finish()
            }
            headTitle.setText("新闻修改")
            headAdd.setImageResource(com.frxuexi.base.R.drawable.ic_action_ok)
            headAdd.setOnClickListener {
                val content = binding.newupContent.text.toString()
                val date = binding.newupDate.text.toString()
                val user = binding.newupUser.text.toString()
                val title = binding.newupTitle.text.toString()

                val item =
                    NewsBeanItem(true, content, nid.toInt(), list, date, true, user, title, type,0)
                vm.sendIntent(NewsIntent.updateNews(nid.toInt(),item))
            }
        }

        ARouter.getInstance().inject(this)

        vm.sendIntent(NewsIntent.getNewsById(nid.toInt()))

        binding.newupType.onItemSelectedListener=object :OnItemSelectedListener{
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                type=typeList.get(position)
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
            }
        }
        binding.newupIv.setOnClickListener {
            PictureSelector.create(this, PictureSelector.SELECT_REQUEST_CODE).selectPicture()
        }

        binding.newaddIvdate.setOnClickListener {
            showDateDialog {
                binding.newupDate.setText(it)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode== PictureSelector.SELECT_REQUEST_CODE && resultCode== RESULT_OK){
            val path = data?.extras?.getParcelable<PictureBean>(PictureSelector.PICTURE_RESULT)?.path!!
            GlideUtil.loadRoundImage(binding.newupIv,path)
            val split = path.split("/")
            val name = split.get(split.lastIndex)
            vm.sendIntent(NewsIntent.uploadNews(name,path))
        }
    }

}